import { subNum } from 'shiptools'
import dayjs from 'dayjs'
import isSameOrAfter  from './dayjs_plugin/isSameOrAfter'
import { WEEK_DAYS } from './constants'
import { STORAGE_KEY } from './storage'
export class Logger {
  info(msg) {
    console.log(
      '%cInfo: %c' + msg,
      'color:#FF0080;font-weight:bold',
      'color: #FF509B'
    )
  }
  warn(msg) {
    console.log(
      '%cWarn: %c' + msg,
      'color:#FF6600;font-weight:bold',
      'color: #FF9933'
    )
  }
  tips(msg) {
    console.log(
      '%cTips: %c' + msg,
      'color:#00B200;font-weight:bold',
      'color: #00CC33'
    )
  }
}


export function delay(delayTime = 500) {
  return new Promise(resolve => {
    setTimeout(() => {
      resolve()
    }, delayTime)
  })
}

/**
 * 将发船周期('0': 全部, '1': 周一, ... '7': 周日)处理成符合前端规范的星期格式(0: 周日, 1: 周一 ... 6: 周六)
 * @param {String} shipCycle 发船周期（英文分号分隔） 
 * @returns {Array} 处理后的发船周期
 */
export function handleShipCycle (shipCycle) {
  let cycle = []
  if(!shipCycle) return []
  if (shipCycle.includes('0')) {
      cycle = [0, 1, 2, 3, 4, 5, 6]
  } else {
      cycle = shipCycle.split(';').map(item => {
          let element = parseInt(item)
          
          // 7周日转化为前端星期表示0
          if (element === 7) { 
              element = 0
          }
          return element
      })
  }
  return cycle
}

export function _toString(val) {
  return val.toString()
}

/**
 * 替换协议
 * -cjsanxia.com 这个图片服务器做特殊处理，替换'https'为'http'
 * @param {String} str 待处理的字符串
 * @returns {String} 替换协议后的字符串
 */
export function replaceProtocol (str) {
  let newStr = str
  // if (str.includes('cjsanxia.com')) {
      newStr = str.replace(/http:/g, 'https:').replace(/\<img/gi, '<img class="rich-img" ');
      // result = result.replace(/\<img/gi, '<img class="rich-img" ');


  // }
  return newStr
}

export function compact(array) {
  var index = -1,
      length = array == null ? 0 : array.length,
      resIndex = 0,
      result = [];

  while (++index < length) {
    var value = array[index];
    if (value) {
      result[resIndex++] = value;
    }
  }
  return result;
}

export const validator = {
  isValid() {
    return true
  }
}


// 获取生日 取整数
export function getAgeInt(birthday) {
  dayjs.extend(isSameOrAfter)
  const nowYear = dayjs().year()
  const birthYear = dayjs(birthday).year()
  // 生日设置 年份设置为当前年
  const birthInYear = dayjs(birthday).set('year', nowYear)
  const nowDate =  dayjs().set('hour', 0).set('minute', 0).set('second', 0)
  return  subNum(subNum(nowYear, birthYear), (birthInYear.isSameOrAfter(nowDate)? 1: 0)) 
}

//根据身份证获取出生年月日和性别
export function getBirthAndSex(idCard) {
  var info = {}
  var birth = (idCard.length === 18) ? idCard.slice(6, 14) : idCard.slice(6, 12)
  var order = (idCard.length === 18) ? idCard.slice(-2, -1) : idCard.slice(-1)
  info.birthDay = (idCard.length === 18) ? ([birth.slice(0, 4), birth.slice(4, 6), birth.slice(-2)]).join('-') : (['19' + birth.slice(0, 2), birth.slice(2, 4), birth.slice(-2)]).join('-')
  info.sex = (order % 1 === 0 ? 1 : 0)
  return info
}


/**
 * 异步弹窗（promise化toast）
 * @param {String} options.title 提示信息
 * @param {String} options.icon 图标，有效值 "success", "loading", "none"
 * @param {String} options.image 自定义图标的本地路径，image 的优先级高于 icon
 * @param {String} options.duration 提示的延迟时间，单位毫秒，默认：1500
 * @param {String} options.mask 是否显示透明蒙层，防止触摸穿透，默认：true
 * @returns {Promise}
 */
export function asyncToast({ title = '', icon = 'none', image = '', duration = 1500, mask = true }) {
  const config = {
      title,
      icon,
      duration,
      mask
  }
  if (image) {
      config.image = image
  }
  return new Promise(resolve => {
      wx.showToast(config)
      const timer = setTimeout(() => {
          clearTimeout(timer)
          resolve()
      }, duration);
  })
}

// 数组去重
export function uniq(arry){
  return [...new Set(arry)]
}



/**
 * 格式化周几或者今天、明天、后天
 * @param {String | Date} date 待处理日期
 * @returns {String} 处理后的日期
 */
export function showDayName(date, withWeek) {
  const today = dayjs().hour(0).minute(0).second(0)
  const dayjsObj = dayjs(date).hour(0).minute(0).second(0)
  let day = '';
  if(withWeek) {
    day = `周${WEEK_DAYS[dayjsObj.day()]}`;
  }
  const days = Math.ceil(dayjsObj.diff(today, 'day', true))
  switch (days) { // 和今天比较天数
      case 0:
          day = ' 今天 ' + day
          break
      case 1:
          day = ' 明天 ' + day
          break
      case 2:
          day = ' 后天 ' + day
          break
      default:
          day = day
  }
  return day
}

export class CountDown {
    constructor() {
      this.timer = null
    }
  
    /**
     * 计时器
     * @param {Number} time 倒计时初始值，单位秒 
     * @param {Function} callback 每次倒计时执行的回调函数
     * @returns {Promise} promise对象，倒计时结束时 
     */
    timing(time, callback) {
        let startTime = time
        const _this = this // 绑定this
        return new Promise(resolve => {
            function timeDown() {
                if (startTime > 0) {
                    callback(startTime)
                    startTime -= 1
                    _this.timer = setTimeout(() => {
                        timeDown()
                    }, 1000)
                } else {
                    _this.clearTimer()
                    resolve()
                }
            }
            timeDown()
        })
    }
    // 清除定时器
    clearTimer() {
        clearTimeout(this.timer)
        this.timer = null
    }
}



export function delayGetScrollOffset({ delayTime = 500 }) {
  return new Promise(resolve => {
    delay(delayTime).then(() => {
      wx.createSelectorQuery()
        .selectViewport()
        .scrollOffset()
        .exec((res) => {
          resolve(res)
        })
    })
  })
}

export function delayGetClientRect({
  self,
  selectorStr,
  delayTime = 500
}) {
  const selector = wx.createSelectorQuery().in(self)
  return new Promise(resolve => {
    delay(delayTime).then(() => {
      selector
        .select(selectorStr)
        .boundingClientRect()
        .exec((res) => {
          resolve(res)
        })
    })
  })
}


export function queryString(param) {
  const query = Object.keys(param).map(k => `${k}=${param[k]}`).join('&');
  return query
}

// 计算 备选时段
export function calculateAlterTime(alternativeTimeType, date) {
    let backUpTime = ''
    switch (Number(alternativeTimeType)) {
        case 0:
            let _nextDay = ''
            const afterThreeHours = dayjs(date).add(1, 'hour').set('hour', 0).set('minute', 0).set('second', 0);
            const beforeHours = dayjs(date).set('hour', 0).set('minute', 0).set('second', 0);
            const diffRes = afterThreeHours.diff(beforeHours, 'day', true)
            if (1 <= diffRes) {
                _nextDay = '次日'
            }
            backUpTime = `${dayjs(date).subtract(1, 'hour').format('HH:mm')}-${_nextDay}${dayjs(date).add(1, 'hour').format('HH:mm')}`
            break;
        case 1:
            let _nextDay1 = ''
            const afterThreeHours1 = dayjs(date).add(3, 'hour').set('hour', 0).set('minute', 0).set('second', 0);
            const beforeHours1 = dayjs(date).set('hour', 0).set('minute', 0).set('second', 0);
            const diffRes1 = afterThreeHours1.diff(beforeHours1, 'day', true)
            if (1 <= diffRes1) {
                _nextDay1 = '次日'
            }
            backUpTime = `${dayjs(date).subtract(3, 'hour').format('HH:mm')}-${_nextDay1}${dayjs(date).add(3, 'hour').format('HH:mm')}`
            break;
        case 2:
            backUpTime = '白天(08:00-18:00)'
            break;
        case 3:
            backUpTime = '全天(00:00-24:00)'
            break;
    }

    return backUpTime;
}



let eventTracer = require('./eventtracer.js')

/**
 * 埋点
 * @param {String} pageName 
 * @param {String} label 
 * @param {String} value 
 */
export function setEvent(pageName, label, value) {
  value = value || '';
  var ev = eventTracer.event({
    pagename: 'pageName',
    productcode: "2045",
    category: "腾讯出行服务-小程序插件",
    action: "船票",
    label: 'label',
    value: 'value',
    debug: true
  });
  ev.settings.pagename = pageName;
  ev.settings.label = label;
  value && (ev.settings.value = value);
  ev.submit();

  console.log('埋点：↓↓↓↓')
  console.log('pageName:', pageName);
  console.log('label:', label);
  console.log('value:', value);
  console.log('\r\n')
}

/**
 * page view
 * @param {*} pagename 
 * @param {*} productCode 
 * @param {*} orgpagename 
 * @param {*} resourceid 
 * @param {*} serialid 
 * @param {*} prepayid 
 * @param {*} unionid 
 * @param {*} innerRefid 
 * @param {*} expandfield 
 * @param {*} adaid 
 * @param {*} rpagename 
 * @param {*} pagestate 
 * @param {*} pagedetail 
 * @param {*} immediately 
 * @param {*} getData 
 */
export function setPage(pagename, productCode = 2045, orgpagename, resourceid, serialid, prepayid, unionid, innerRefid, expandfield, adaid='', rpagename = '', pagestate = '', pagedetail = '', immediately = false, getData) {
  if (pagename.indexOf('wxrefid=') < 0) {
    var wxrefid = pagename.indexOf('?') < 0 ? '?wxrefid=' : '&wxrefid='
    pagename = pagename + wxrefid + wx.getStorageSync(STORAGE_KEY.shipRefId);
  }
  eventTracer.page({
    pagename: pagename, //页面名称，一个完整的视图的路径
    orgpagename: orgpagename || "", //上一个页面的视图路径
    productcode: productCode, //产品码     "度假"(出境）;
    resourceid: resourceid || 0, //资源ID
    serialid: serialid || '',//
    prepayid: prepayid || '',  //支付ID
    unionid: unionid || '',    //用户unionid
    innerRefid: innerRefid || '',//小程序内页面间跳转传递refid
    expandfield: expandfield || '',//自定义数据（String）
    adaid: adaid,//广告id
    rpagename,//根页面名称
    pagestate,//页面状态
    pagedetail,//页面浏览详情
    immediately,//是否立即上报
    getData,//机票获取上报参数回调
  }).submit()
}